const axios = require('axios');
const cheerio = require('cheerio');
const { geminiAI } = require('../google/gemini')
const { generateNewsPrompt } = require('../utils/newsPrompt')
const DateFormat = require('../utils/dateFormat')
const { writeSheet } = require('../google/sheet')
const { checkAuth, sendMail } = require('../google/gmail')

// 步骤1: 获取新闻联播页面git
async function fetchNewsPage (formattedDate) {
    const url = `https://tv.cctv.com/lm/xwlb/day/${formattedDate}.shtml`;
    const response = await axios.get(url);
    return response.data;
}
// 步骤2: 解析新闻列表
function parseNewsList (html) {
    const $ = cheerio.load(html);
    const urls = [];

    $('li>a').each((i, elem) => {
        urls.push($(elem).attr('href'));
    });

    return { urls };
}
// 步骤3: 获取详细新闻内容
async function fetchMainNewsContent (url) {
    const response = await axios.get(url);
    return response.data;
}
// 步骤4: 解析详细新闻内容
function parseMainNewsContent (html) {
    const $ = cheerio.load(html);
    const titleStr = $('.nrjianjie_shadow ul>li>p').html() || '';
    return titleStr.split(/\n\d{1}/).filter(t => t.trim() !== '');
}
// 步骤5: AI-AGENT 
async function analyzeNewsWithAI (prompt) {
    return await geminiAI(prompt)
}
// 步骤6: 解析AI输出格式化
function parseAIOutput (output, formattedDate) {
    const contentArr = output.split('\n\n---\n');
    const datas = [];

    for (let i = 1; i < contentArr.length; i++) {
        let [content1, videoUrl] = contentArr[i].split('🔗[视频链接]');
        let item = content1.split(/\n(?=\w)/);

        const title = item[0];
        const cmContent = item[1] || '';
        const keynote = item[2] || '';
        let aboutMe = item[3] || '';

        let urlMatch = /\((.*)\)/.exec(videoUrl);
        let url = urlMatch ? urlMatch[1] : '';

        datas.push([
            formattedDate,
            title,
            cmContent,
            keynote,
            aboutMe,
            url
        ]);
    }

    return datas;
}
// 步骤7: 写入googleSheet
async function writeToGoogleSheets (data) {
    await writeSheet('dailyNews', data)
}
// 步骤8: 发送谷歌邮件
async function sendEmail (content, formattedDate) {
    // 发送邮件
    return await sendMail(`${formattedDate}新闻联播内容解析`, content)
}
//执行整个工作流
async function executeNewsWorkflow () {
    try {
        // 检查gmail。token 是否过期
        const resAuth = await checkAuth()
        console.log(resAuth)
        if (resAuth.code != 200) {
            console.log('邮件token过期!!!!!')
            console.log(resAuth.msg)
            return resAuth
        }
        const dateFormat = new DateFormat()
        console.log(`当前时间: ${dateFormat.format()}`);
        // 判断当前时间是否超21点
        const formattedDate = dateFormat.date.getHours() < 21 ? dateFormat.minus(1).format() : dateFormat.format()
        // 获取新闻联播页面
        const newsPageHtml = await fetchNewsPage(formattedDate);
        console.log(`成功获取${formattedDate}新闻联播页面`);

        // 解析新闻列表
        const { urls } = parseNewsList(newsPageHtml);
        const mainUrl = urls[0];
        console.log(`找到 ${urls.length} 条新闻`);

        // 获取详细新闻内容 
        const mainNewsHtml = await fetchMainNewsContent(mainUrl);
        console.log('成功获取详细新闻内容');

        // 解析详细新闻内容
        const titleArr = parseMainNewsContent(mainNewsHtml);
        const urlArr = urls.slice(1);

        // 构造新闻数据
        const newsData = [];
        for (let i = 1; i < titleArr.length; i++) {
            newsData.push({
                title: titleArr[i],
                url: urlArr[i - 1]
            });
        }
        console.log('成功构造新闻数据');
        console.log(JSON.stringify(newsData))

        // AI分析新闻内容
        const aiOutput = await analyzeNewsWithAI(generateNewsPrompt(newsData, mainUrl, dateFormat.format('yyyy年MM月dd号')));
        console.log('AI分析完成');

        // 解析AI输出
        const parsedData = parseAIOutput(aiOutput, formattedDate)
        // console.log(`解析得到 ${parsedData.length} 条结构化数据`);

        // 写入Google Sheets
        await writeToGoogleSheets(parsedData);
        console.log('数据写入Google Sheets完成');

        // 发送邮件
        await sendEmail(aiOutput, formattedDate);
        console.log('邮件发送完成');

        console.log('工作流执行完成');
        return { success: true, data: parsedData };

    } catch (error) {
        console.error('工作流执行出错:', error);
        return { success: false, error: error.message };
    }
}

module.exports = { executeNewsWorkflow };